/*
 * Copyright (c) 2002-2007, Mairie de Paris
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice
 *     and the following disclaimer.
 *
 *  2. Redistributions in binary form must reproduce the above copyright notice
 *     and the following disclaimer in the documentation and/or other materials
 *     provided with the distribution.
 *
 *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * License 1.0
 */
package fr.paris.lutece.plugins.customisation.business.tab;

import fr.paris.lutece.portal.business.portlet.Portlet;
import fr.paris.lutece.portal.business.portlet.PortletHome;
import fr.paris.lutece.util.ReferenceList;
import fr.paris.lutece.util.sql.DAOUtil;

import java.sql.Timestamp;

import java.util.ArrayList;
import java.util.List;


/**
 * This class provides Data Access methods for CustomisationTab objects
 */
public class CustomisationTabDAO implements ICustomisationTabDAO
{
    // Constants
    private static final String SQL_QUERY_NEW_PK_TAB = " SELECT max(id_tab) FROM customisation_tab ";
    private static final String SQL_QUERY_SELECT_TAB = "SELECT * FROM customisation_tab WHERE id_tab = ? ORDER BY order_tab ";
    private static final String SQL_QUERY_INSERT_TAB = "INSERT INTO customisation_tab ( id_tab, name_tab, mylutece_database_user_id, order_tab, id_template, code_theme, date_creation, date_update, first_col_width, second_col_width, third_col_width )" +
        " VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ";
    private static final String SQL_QUERY_UPDATE_TAB = "UPDATE customisation_tab SET name_tab = ?, order_tab = ?, id_template = ?, code_theme = ?, date_update = ?, first_col_width = ?, second_col_width = ?, third_col_width = ? WHERE id_tab = ? AND mylutece_database_user_id = ? ";
    private static final String SQL_QUERY_DELETE_TAB = "DELETE FROM customisation_tab WHERE id_tab = ? AND mylutece_database_user_id = ?";
    private static final String SQL_QUERY_SELECT_ALL_TAB_BY_USER = "SELECT * FROM customisation_tab WHERE mylutece_database_user_id = ? ORDER BY order_tab";
    private static final String SQL_QUERY_SELECT_PORTLET_BY_TAB = " SELECT id_portlet FROM customisation_user_portlet WHERE id_tab = ? ORDER BY portlet_order ";
    private static final String SQL_QUERY_SELECT_CHECK_USER = " SELECT * FROM customisation_tab WHERE mylutece_database_user_id = ? ";
    private static final String SQL_QUERY_COUNT_TAB_BY_USER = " SELECT COUNT(id_tab) FROM customisation_tab WHERE mylutece_database_user_id = ? ";

    private static final String SQL_QUERY_UPDATE_ORDER_TAB = "UPDATE customisation_tab SET order_tab = ? WHERE id_tab = ? AND mylutece_database_user_id = ? ";
    
    
    
    /**
     * Load the data of a tab in a specific tab from the database
     *
     * @param nIdTab the tab identifier
     * @param strUserName
     * @return  the object tab initialized with the data of the database
     */
    public CustomisationTab load( int nIdTab )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_TAB );
        daoUtil.setInt( 1, nIdTab );
        daoUtil.executeQuery(  );

        CustomisationTab tab = new CustomisationTab(  );

        if ( daoUtil.next(  ) )
        {
            tab.setIdTab( daoUtil.getInt( 1 ) );
            tab.setNameTab( daoUtil.getString( 2 ) );
            tab.setUserId( daoUtil.getString( 3 ) );
            tab.setOrderTab( daoUtil.getInt( 4 ) );
            tab.setIdTemplate( daoUtil.getInt( 5 ) );
            tab.setCodeTheme( daoUtil.getString( 6 ) );
            tab.setFirstColumnWidth(daoUtil.getInt(9));
            tab.setSecondColumnWidth(daoUtil.getInt( 10 ));
            tab.setThirdColumnWidth(daoUtil.getInt( 11 ));
        }

        daoUtil.free(  );

        return tab;
    }

    /**
     * Returns a new primary key which will be used to add a new tab
     *
     * @return The new key.
     */
    private int newPrimaryKey(  )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_NEW_PK_TAB );
        daoUtil.executeQuery(  );

        int nKey;

        if ( !daoUtil.next(  ) )
        {
            nKey = 1;
        }

        nKey = daoUtil.getInt( 1 ) + 1;

        daoUtil.free(  );

        return nKey;
    }

    /**
     * Insert a new record in the table
     *
     * @param strNameTab the tab name
     * @param strUserName the user identifier
     * @param nOrderTab the order of the tab
     * @param nIdTemplate the template identifier
     * @param strCodeTheme the code of the theme
     */
    public void insert( String strNameTab, String strUserName, int nOrderTab, int nIdTemplate, String strCodeTheme, int firstColumnWidth, int secondColumnWidth, int thirdColumnWidth  )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_INSERT_TAB );

        int nNewPrimaryKey = newPrimaryKey(  );

        increaseOrderTab( nOrderTab, strUserName);
        
        daoUtil.setInt( 1, nNewPrimaryKey );
        daoUtil.setString( 2, strNameTab );
        daoUtil.setString( 3, strUserName );
        daoUtil.setInt( 4, nOrderTab );
        daoUtil.setInt( 5, nIdTemplate );
        daoUtil.setString( 6, strCodeTheme );
        daoUtil.setTimestamp( 7, new Timestamp( new java.util.Date(  ).getTime(  ) ) );
        daoUtil.setTimestamp( 8, new Timestamp( new java.util.Date(  ).getTime(  ) ) );
        daoUtil.setInt(9, firstColumnWidth);
        daoUtil.setInt(10, secondColumnWidth);
        daoUtil.setInt(11, thirdColumnWidth);
        daoUtil.executeUpdate(  );

        daoUtil.free(  );
    }

    /**
     * Update the record in the table
     *
     * @param nIdTab the tab identifier
     * @param strNameTab the tab name
     * @param strUserName the user identifier
     * @param nOrderTab the order of the tab
     * @param nIdTemplate the template identifier
     * @param strCodeTheme the code of the theme
     */
    public void store( int nIdTab, String strNameTab, String strUserName, int nOrderTab, int nIdTemplate,
        String strCodeTheme,int firstColumnWidth, int secondColumnWidth, int thirdColumnWidth )
    {
    	increaseOrderTab( nOrderTab, strUserName);
    	
    	DAOUtil daoUtil = new DAOUtil( SQL_QUERY_UPDATE_TAB );
        daoUtil.setInt( 9, nIdTab );
        daoUtil.setString(10, strUserName );
        daoUtil.setString( 1, strNameTab );
        daoUtil.setInt( 2, nOrderTab );
        daoUtil.setInt( 3, nIdTemplate );
        daoUtil.setString( 4, strCodeTheme );
        daoUtil.setTimestamp( 5, new Timestamp( new java.util.Date(  ).getTime(  ) ) );
        daoUtil.setInt(6, firstColumnWidth);
        daoUtil.setInt(7, secondColumnWidth);
        daoUtil.setInt(8, thirdColumnWidth);
        daoUtil.executeUpdate(  );
        daoUtil.free(  );
    }

    /**
     * Delete a record from the table
     *
     * @param nIdTab the tab identifier
     * @param strUserName the user identifier
     */
    public void delete( int nIdTab, String strUserName )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE_TAB );
        daoUtil.setInt( 1, nIdTab );
        daoUtil.setString( 2, strUserName );

        daoUtil.executeUpdate(  );
        daoUtil.free(  );
    }

    /**
     * Returns a list of tabs according the user identifier
     *
     * @param strUserName the user identifier
     * @return the user's tab in form of Collection
     */
    public List<CustomisationTab> selectTabUser( String strUserName )
    {
        List<CustomisationTab> listTabUser = new ArrayList<CustomisationTab>(  );
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_ALL_TAB_BY_USER );
        daoUtil.setString( 1, strUserName );
        daoUtil.executeQuery(  );

        while ( daoUtil.next(  ) )
        {
            CustomisationTab tab = new CustomisationTab(  );

            tab.setIdTab( daoUtil.getInt( 1 ) );
            tab.setNameTab( daoUtil.getString( 2 ) );
            tab.setUserId( daoUtil.getString( 3 ) );
            tab.setOrderTab( daoUtil.getInt( 4 ) );
            tab.setIdTemplate( daoUtil.getInt( 5 ) );
            tab.setCodeTheme( daoUtil.getString( 6 ) );
            listTabUser.add( tab );
        }

        daoUtil.free(  );
        
        for ( int i = 0; i < listTabUser.size(  ); i++ )
        {
	        DAOUtil daoUtil2 = new DAOUtil( SQL_QUERY_UPDATE_ORDER_TAB );
	        daoUtil2.setInt( 1, i + 1 );
	        daoUtil2.setInt( 2, listTabUser.get( i ).getIdTab(  ) );
	        daoUtil2.setString( 3, strUserName );
	        daoUtil2.executeUpdate(  );
	        daoUtil2.free(  );
        }	

        return listTabUser;
    }

    /**
     * Returns the list of a tab according the user identifier
     *
     * @param strUserName the user identifier
     * @return the list of a tab according the user identifier
     */
    public ReferenceList selectAllTabUser( String strUserName )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_ALL_TAB_BY_USER );
        daoUtil.setString( 1, strUserName );
        daoUtil.executeQuery(  );

        ReferenceList listTab = new ReferenceList(  );

        while ( daoUtil.next(  ) )
        {
            listTab.addItem( daoUtil.getInt( 1 ), daoUtil.getString( 2 ) );
        }

        daoUtil.free(  );

        return listTab;
    }

    /**
     * Returns a list of tabs according the user identifier and the tab identifier
     *
     * @param nIdTab the tab identifier
     * @return the user's portlet according a tab in form of Collection
     */
    public List<Portlet> loadPortlets( int nIdTab ) // ID de l'USER
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_PORTLET_BY_TAB );
        daoUtil.setInt( 1, nIdTab );
        daoUtil.executeQuery(  );

        CustomisationTab tab = CustomisationTabHome.findByPrimaryKey( nIdTab );
        ArrayList<Portlet> listPortlets = new ArrayList<Portlet>(  );

        while ( daoUtil.next(  ) )
        {
            int nPortletId = daoUtil.getInt( 1 );
            Portlet portlet = PortletHome.findByPrimaryKey( nPortletId );
            listPortlets.add( portlet );
        }

        tab.setPortlets( listPortlets );
        daoUtil.free(  );

        return listPortlets;
    }

    /**
     * Returns the last tab created by the User
     *
     * @param strUserName The user identifier
     * @return the last tab created by the User
     */
    public int selectLastTab( String strUserName )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_NEW_PK_TAB );
        daoUtil.executeQuery(  );

        int lastTab = 0;

        while ( daoUtil.next(  ) )
        {
            lastTab = daoUtil.getInt( 1 );
        }

        daoUtil.free(  );

        return lastTab;
    }

    /**
     * Returns a boolean condition about the presence or not of an user
     *
     * @param strUserName The user identifier
     * @return a boolean condition
     */
    public boolean checkUser( String strUserName )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_CHECK_USER );
        daoUtil.setString( 1, strUserName );
        daoUtil.executeQuery(  );

        boolean bExists = false;

        while ( daoUtil.next(  ) )
        {
            bExists = true;
        }

        daoUtil.free(  );

        return bExists;
    }

    /**
     * Returns the tab's number for an user
     *
     * @param strUserName The user identifier
     * @return The tab's number for an user
     */
    public int selectCountTabByUser( String strUserName )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_COUNT_TAB_BY_USER );
        daoUtil.setString( 1, strUserName );
        daoUtil.executeQuery(  );

        int countTab = 0;

        while ( daoUtil.next(  ) )
        {
            countTab = daoUtil.getInt( 1 );
        }

        daoUtil.free(  );

        return countTab;
    }
    
	/**
	 * Updates the order for all tabs for an user specified
	 * 
	 * @param nTabId the tab identifier
	 * @param strUserName the user identifier
	 */
    private void increaseOrderTab( int nTabId ,String strUserName )
    {
    	List<CustomisationTab> listTab = selectTabUser( strUserName );
    	
        for ( int i = 0; i < listTab.size(  ); i++ )
        {
        	if ( ( listTab.get( i ).getOrderTab(  ) >= nTabId ) )
        	{
	        	DAOUtil daoUtil = new DAOUtil( SQL_QUERY_UPDATE_ORDER_TAB );
		        daoUtil.setInt( 1, listTab.get( i ).getOrderTab(  ) + 1 );
		        daoUtil.setInt( 2, listTab.get( i ).getIdTab(  ) );
		        daoUtil.setString( 3, strUserName );
		        daoUtil.executeUpdate(  );
		        daoUtil.free(  );
        	}
        }
    }
    
}
